package TCP;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Author YuanYuan
 * @Date 2022/10/16
 * @Time 18:03
 */
public class TcpEchoClient {
    public Socket socket = null;

    public TcpEchoClient(String severIP,int severPort) throws IOException {
        //和服务器建立连接,需要知道服务器在哪
        socket = new Socket(severIP,severPort);
    }

    public void start() throws FileNotFoundException {
        Scanner scanner = new Scanner(System.in);
        try(OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream()) {
            while (true) {
                //1.从控制台读取数据,构造成一个请求
                System.out.print("->");
                String requestStr = scanner.next();
                //2.将请求发给服务器
                PrintWriter requestPrintWriter = new PrintWriter(outputStream);
                requestPrintWriter.println(requestStr);
                //如果不flush,可能导致请求没有真发出去
                requestPrintWriter.flush();
                //3.从服务器读取Tcp响应数据
                Scanner response = new Scanner(inputStream);
                String responseStr = response.next();
                //4.把响应显示到界面上
                System.out.println(responseStr);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9000);
        tcpEchoClient.start();
    }
}
